package com.example.musicapp.view;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;

import android.content.ServiceConnection;


import android.os.Build;
import android.os.Handler;
import android.os.IBinder;

import android.view.MenuInflater;

import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;


import com.example.musicapp.R;
import com.example.musicapp.application.MyApp;
import com.example.musicapp.base.BaseActivity;
import com.example.musicapp.bean.Music;
import com.example.musicapp.contract.IPlayContract;
import com.example.musicapp.presenter.PlayPresenter;
import com.example.musicapp.service.MediaService;

import com.example.musicapp.utils.ImageLoader;
import com.google.android.material.imageview.ShapeableImageView;

import java.text.SimpleDateFormat;

import java.util.List;

import static com.example.musicapp.service.MediaService.PLAY_STATION;
import static com.example.musicapp.service.MediaService.sPlayPosition;
import static com.example.musicapp.utils.Constant.ORDER_PLAY;
import static com.example.musicapp.utils.Constant.RANDOM_PLAY;
import static com.example.musicapp.utils.Constant.SINGLE_CYCLE_PLAY;


public class PlayActivity extends BaseActivity<PlayPresenter> implements IPlayContract.IPlayUi, View.OnClickListener {

    private final Handler mHandler = new Handler();

    private MediaService.MyBinder mMyBinder;
    private ImageView playButton;
    private SeekBar mSeekBar;
    private TextView mTextView;
    //进度条下面的当前进度文字，将毫秒化为m:ss格式
    private final SimpleDateFormat time = new SimpleDateFormat("m:ss");
    //“绑定”服务的intent
    Intent MediaServiceIntent;
    private List<Music> mList;
    private int mPosition;
    private TextView mTvSong;
    private TextView mTvSongTime;
    private ShapeableImageView mIvDisk;
    private TextView mTvSinger;
    /**
     * 图片动画
     */
    private ObjectAnimator logoAnimation;

    @Override
    public PlayPresenter onBindPresenter() {
        return new PlayPresenter(this);
    }

    @Override
    protected void initData() {
        logoAnimation.start();
        MediaServiceIntent = new Intent(this, MediaService.class);
        bindService(MediaServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        Intent intent = getIntent();
        mPosition = intent.getIntExtra("position", 0);
        mList = (List<Music>) intent.getSerializableExtra("musicList");
        mTvSongTime.setText(time.format(mList.get(mPosition).getDuration()) + "s");
        mTvSong.setText(mList.get(mPosition).getSong() + "-" + mList.get(mPosition).getSinger());
        ImageLoader.getInstance(this).bindBitmap(mList.get(mPosition).getAlbumHd(),mIvDisk);
    }

    @Override
    protected void initView() {
        Button mBtnPlayMode = findViewById(R.id.btn_play_mode);
        mTvSinger = findViewById(R.id.tv_singer_name);
        mIvDisk = findViewById(R.id.iv_disk);
        playButton = findViewById(R.id.playing_play);
        ImageView nextButton = findViewById(R.id.playing_next);
        ImageView preciousButton = findViewById(R.id.playing_pre);
        mSeekBar = findViewById(R.id.music_seek_bar);
        mTextView = findViewById(R.id.text_time);
        mTvSong = findViewById(R.id.tv_song);
        mTvSongTime = findViewById(R.id.tv_song_time);
        playButton.setOnClickListener(this);
        nextButton.setOnClickListener(this);
        preciousButton.setOnClickListener(this);
        mBtnPlayMode.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(PlayActivity.this,v);
            //获取菜单填充器
            MenuInflater inflater = popup.getMenuInflater();

            //填充菜单
            inflater.inflate(R.menu.menu_play_mode, popup.getMenu());
            //绑定菜单项的点击事件
            popup.setOnMenuItemClickListener(item -> {

                switch (item.getItemId()) {
                    case R.id.item_order_play:
                        Toast.makeText(MyApp.getContext(), "设置为循序播放", Toast.LENGTH_SHORT).show();
                        mMyBinder.setMode(ORDER_PLAY);
                        break;
                    case R.id.item_single_circle_play:
                        mMyBinder.setMode(SINGLE_CYCLE_PLAY);
                        Toast.makeText(MyApp.getContext(), "设置为单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.item_random_play:
                        mMyBinder.setMode(RANDOM_PLAY);
                        Toast.makeText(MyApp.getContext(), "设置为随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }


                return false;
            });
            //显示(这一行代码不要忘记了)
            popup.show();
        });
        initAnimation();

    }


    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMyBinder = (MediaService.MyBinder) service;
//            mMediaService = ((MediaService.MyBinder) service).getInstance();
            mMyBinder.setMode(ORDER_PLAY);
            mMyBinder.registerViewController(mIPlayViewControl);
            mMyBinder.setMusicList(mList, mPosition);
            mSeekBar.setMax(mMyBinder.getProgress());

            mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    //这里很重要，如果不判断是否来自用户操作进度条，会不断执行下面语句块里面的逻辑，然后就会卡顿卡顿
                    if (fromUser) {
                        mMyBinder.seekToPositon(seekBar.getProgress());
//                    mMediaService.mMediaPlayer.seekTo(seekBar.getProgress());
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            mHandler.post(mRunnable);

            mMyBinder.playMusic();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //我们的handler发送是定时1000s发送的，如果不关闭，MediaPlayer release掉了还在获取getCurrentPosition就会爆IllegalStateException错误
        mHandler.removeCallbacks(mRunnable);

        unbindService(mServiceConnection);
    }

    /**
     * 更新ui的runnable
     */
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mSeekBar.setProgress(mMyBinder.getPlayPosition());
            mTextView.setText(time.format(mMyBinder.getPlayPosition()) + "s");
            mHandler.postDelayed(mRunnable, 1000);
        }
    };

    @Override
    public void initListener() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_play;
    }

    @Override
    public void onClick(View v) {



        switch (v.getId()) {
            case R.id.playing_play:
                mMyBinder.playMusic();

                logoAnimation.start();
                if (PLAY_STATION == 1){
                    logoAnimation.start();
                }else if (PLAY_STATION == 0){
                    logoAnimation.pause();
                }

                break;
            case R.id.playing_next:
                mMyBinder.nextMusic();

                changUi(sPlayPosition);

                break;
            case R.id.playing_pre:

                mMyBinder.preciousMusic();
                changUi(sPlayPosition);


                break;
        }
    }


    /**
     * 实现类进行对UI按钮的改变
     */
    private final IPlayViewControl mIPlayViewControl = new IPlayViewControl() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPlayerStateChange(int state) {
            //根据播放界面修改UI
            switch (state) {
                case 0:
                    //播放改成暂停
                    runOnUiThread(() -> playButton.setImageResource(R.drawable.ic_baseline_play_circle_filled_24));

                    break;
                case 1:
                    //暂停改成播放
                    runOnUiThread(() -> playButton.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24));

                    break;
                default:
                    break;

            }
        }
    };

    /**
     * 根据歌曲改变ui
     * @param position 歌曲位置
     */
    private void changUi(int position) {

        mTvSongTime.setText(time.format(mList.get(position).getDuration()) + "s");
        mTvSong.setText(mList.get(position).getSong() );
        mTvSong.setSelected(true);
        mTvSinger.setText(mList.get(position).getSinger());
        ImageLoader.getInstance(this).bindBitmap(mList.get(position).getAlbumHd(),mIvDisk);

    }

    /**
     * 初始化动画
     */
    private void initAnimation() {
        logoAnimation = ObjectAnimator.ofFloat(mIvDisk, "rotation", 0.0f, 360.0f);
        logoAnimation.setDuration(20000);
        logoAnimation.setInterpolator(new LinearInterpolator());
        logoAnimation.setRepeatCount(-1);
        logoAnimation.setRepeatMode(ObjectAnimator.RESTART);
    }





}
